package com.itrip.log.module.collect;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.itrip.log.core.AbstractModule;
import com.itrip.log.core.BootstrapServer;
import com.itrip.log.core.ThreadPools;
import com.itrip.log.module.db.DBModule;
import com.itrip.log.module.db.domain.HostBean;
import com.itrip.log.module.db.server.ConfigManager;
import com.itrip.log.module.db.server.HostManager;

/**
 * Function:采集模块,在主机配置变化时添加或删除主机时重建链接
 *
 * @date:2016年10月19日/下午6:45:00
 * @Author:coder_czp@126.com
 * @version:1.0
 */
public class CollectModule extends AbstractModule<ILogInputStream> {

	private static final Logger LOG = LoggerFactory.getLogger(CollectModule.class);

	private ConfigManager configManager;

	private HostManager hostManager;

	private BootstrapServer boot;

	public HostManager getHostManager() {
		return hostManager;
	}

	public void setHostManager(HostManager hostManager) {
		this.hostManager = hostManager;
	}

	@Override
	public String name() {
		return "CollectModule";
	}

	@Override
	public void start(BootstrapServer root) {

		this.boot = root;
		this.configManager = root.getModuleServer(DBModule.class, ConfigManager.class);

		for (HostBean hostBean : hostManager.getHosts()) {
			servers.add(new TailfInputStream(hostBean, configManager));
		}

		for (ILogInputStream item : servers) {
			item.setBoostServer(root);
			item.start();
		}
	}

	@Override
	public void stop(BootstrapServer root) {
		for (ILogInputStream item : servers) {
			stopInputStream(item);
		}

	}

	/***
	 * 停止采集某台机器的信息
	 * 
	 * @param host
	 * @return
	 */
	public boolean stopCollect(HostBean host) {
		for (ILogInputStream item : servers) {
			if (item instanceof IRemoteLogInputStream) {
				IRemoteLogInputStream rSer = (IRemoteLogInputStream) item;
				if (rSer.getRemoteHost().equals(host)) {
					stopInputStream(item);
					return servers.remove(item);
				}
			}
		}
		return false;
	}

	/***
	 * 重建某台主机的链接,例如密码改变等操场
	 * 
	 * @param host
	 * @return
	 */
	public boolean reConnectHost(HostBean host) {
		if (stopCollect(host)) {
			return startCollect(host);
		}
		return false;
	}

	/***
	 * 开始采集某台机器,用于新增机器
	 * 
	 * @param host
	 * @return
	 */
	public boolean startCollect(HostBean host) {
		TailfInputStream item = new TailfInputStream(host, configManager);
		if (servers.contains(item)) {
			LOG.info("want to start collect {},but aready exist", host);
			return false;
		}

		servers.add(item);
		item.setBoostServer(boot);
		ThreadPools.getInstance().startThread(item.name(), item);
		return true;
	}

	private void stopInputStream(ILogInputStream item) {
		try {
			item.stop();
		} catch (Exception e) {
			LOG.error("fail to stop:" + item, e);
		}
	}
}
